package com.example.traning.security.util;

import cn.hutool.core.util.IdUtil;
import com.example.traning.security.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import lombok.experimental.UtilityClass;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author lei yu
 * @since 2024/10/14
 */
@UtilityClass
public class SecurityUtils {

    private final List<String> TOKEN_CACHE = new ArrayList<>();

    public String setToken() {
        String token = IdUtil.nanoId();
        TOKEN_CACHE.add(token);
        return token;
    }

    public String getToken() {
        if (TOKEN_CACHE.isEmpty()) {
            return "";
        }
        return TOKEN_CACHE.getFirst();
    }

    /**
     * 设置当前用户
     *
     * @param loginUser 登录用户
     * @param request 请求
     */
    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
        // 创建 Authentication，并设置到上下文
        Authentication authentication = buildAuthentication(loginUser, request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {
        // 创建 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, Collections.emptyList());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }
}
